"""
# -*- coding: utf-8 -*-
# @Time    : 2023/6/12 16:04
# @Author  : 王摇摆
# @FileName: nn_iris.py
# @Software: PyCharm
# @Blog    ：https://blog.csdn.net/weixin_44943389?type=blog
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # 设置TensorFlow日志级别为"ERROR"
import time

## 加载工具库
from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import SGD
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.datasets import load_iris

## 载入 Iris 数据集，然后进行训练集和测试集的划分，80%数据作为训练集，其余20%作为测试集
print("1. 正在加载数据集...")
time.sleep(1)
dataset = load_iris()
(trainX, testX, trainY, testY) = train_test_split(dataset.data,
                                                  dataset.target, test_size=0.2)

print("2. 数据集正在预处理...")
time.sleep(1)
## 将标签进行独热向量编码
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)

print("3. 正在构建模型...")
time.sleep(1)
## 利用 Keras 定义网络模型
model = Sequential()
model.add(Dense(3, input_shape=(4,), activation="sigmoid"))
model.add(Dense(3, activation="sigmoid"))
model.add(Dense(3, activation="softmax"))

## 采用梯度下降训练模型
opt = SGD(lr=0.1, momentum=0.9, decay=0.1 / 250)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=["accuracy"])
print("4. 正在训练模型...")
time.sleep(1)
H = model.fit(trainX, trainY, validation_data=(testX, testY), epochs=250, batch_size=16)

## 预测
print("5. 模型正在推理...")
time.sleep(1)
predictions = model.predict(testX, batch_size=16)
print("6. 正在评估模型...")
time.sleep(1)
print(classification_report(testY.argmax(axis=1), predictions.argmax(axis=1), target_names=dataset.target_names))
